<template>
  <div>
    <h2>历史趋势分析</h2>
    
    <el-row :gutter="20" class="mb-4">
      <el-col :span="6">
        <el-select v-model="selectedPlot" placeholder="选择地块" clearable>
          <el-option label="全部地块" value="" />
          <el-option label="P001" value="P001" />
          <el-option label="P002" value="P002" />
          <el-option label="P003" value="P003" />
          <el-option label="P004" value="P004" />
          <el-option label="P005" value="P005" />
        </el-select>
      </el-col>
      <el-col :span="10">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :shortcuts="dateShortcuts"
        />
      </el-col>
      <el-col :span="4">
        <el-button type="primary" @click="updateChart">更新图表</el-button>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="24">
        <el-card>
          <template #header>
            <span>土壤指标趋势图</span>
          </template>
          <v-chart :option="trendChartOption" style="height: 400px" />
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="mt-4">
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>pH值分布</span>
          </template>
          <v-chart :option="phDistributionOption" style="height: 300px" />
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>SOC含量变化</span>
          </template>
          <v-chart :option="socTrendOption" style="height: 300px" />
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="mt-4">
      <el-col :span="24">
        <el-card>
          <template #header>
            <span>数据对比分析</span>
          </template>
          <el-table :data="comparisonData" style="width: 100%">
            <el-table-column prop="period" label="时间段" />
            <el-table-column prop="avg_ph" label="平均pH" />
            <el-table-column prop="avg_soc" label="平均SOC (%)" />
            <el-table-column prop="ph_change" label="pH变化" />
            <el-table-column prop="soc_change" label="SOC变化" />
            <el-table-column prop="trend" label="趋势">
              <template #default="{ row }">
                <el-tag :type="getTrendType(row.trend)">{{ row.trend }}</el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getTrendData } from '../api/dashboard'

const selectedPlot = ref('')
const dateRange = ref([
  new Date(Date.now() - 30 * 24 * 60 * 60 * 1000), // 30天前
  new Date()
])

const dateShortcuts = [
  {
    text: '最近7天',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    }
  },
  {
    text: '最近30天',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    }
  },
  {
    text: '最近90天',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    }
  }
]

const trendChartOption = ref({
  title: { text: '土壤指标历史趋势' },
  tooltip: { trigger: 'axis' },
  legend: { data: ['pH值', 'SOC (%)', '湿度 (%)', '温度 (°C)'] },
  grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
  xAxis: { type: 'category', boundaryGap: false },
  yAxis: { type: 'value' },
  series: [
    {
      name: 'pH值',
      type: 'line',
      smooth: true,
      data: []
    },
    {
      name: 'SOC (%)',
      type: 'line',
      smooth: true,
      data: []
    },
    {
      name: '湿度 (%)',
      type: 'line',
      smooth: true,
      data: []
    },
    {
      name: '温度 (°C)',
      type: 'line',
      smooth: true,
      data: []
    }
  ]
})

const phDistributionOption = ref({
  title: { text: 'pH值分布' },
  tooltip: { trigger: 'axis' },
  xAxis: { type: 'category', data: ['4.0-5.0', '5.0-6.0', '6.0-6.5', '6.5-7.0', '7.0-7.5', '7.5-8.0', '8.0-9.0'] },
  yAxis: { type: 'value' },
  series: [{
    data: [2, 8, 15, 25, 20, 12, 3],
    type: 'bar',
    itemStyle: {
      color: new Function('return ' + `
        new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: '#83bff6' },
          { offset: 0.5, color: '#188df0' },
          { offset: 1, color: '#188df0' }
        ])
      `)()
    }
  }]
})

const socTrendOption = ref({
  title: { text: 'SOC含量变化趋势' },
  tooltip: { trigger: 'axis' },
  xAxis: { type: 'category' },
  yAxis: { type: 'value', name: 'SOC (%)' },
  series: [{
    type: 'line',
    smooth: true,
    areaStyle: {},
    data: [2.35, 2.38, 2.41, 2.36, 2.33, 2.35, 2.37, 2.40, 2.42, 2.39]
  }]
})

const comparisonData = ref([
  {
    period: '2024-10-11 ~ 2024-10-20',
    avg_ph: 6.8,
    avg_soc: 2.35,
    ph_change: '+0.1',
    soc_change: '+0.02',
    trend: '上升'
  },
  {
    period: '2024-10-21 ~ 2024-10-30',
    avg_ph: 6.9,
    avg_soc: 2.33,
    ph_change: '+0.1',
    soc_change: '-0.02',
    trend: '波动'
  },
  {
    period: '2024-10-31 ~ 2024-11-09',
    avg_ph: 6.7,
    avg_soc: 2.36,
    ph_change: '-0.2',
    soc_change: '+0.03',
    trend: '改善'
  }
])

const getTrendType = (trend) => {
  const types = {
    '上升': 'success',
    '下降': 'danger',
    '波动': 'warning',
    '改善': 'success'
  }
  return types[trend] || 'info'
}

const updateChart = async () => {
  try {
    const response = await getTrendData(
      selectedPlot.value,
      dateRange.value[0],
      dateRange.value[1]
    )
    
    trendChartOption.value.xAxis.data = response.labels
    trendChartOption.value.series[0].data = response.datasets[0].data
    trendChartOption.value.series[1].data = response.datasets[1].data
    trendChartOption.value.series[2].data = response.datasets[2]?.data || []
    trendChartOption.value.series[3].data = response.datasets[3]?.data || []
  } catch (error) {
    console.error('获取趋势数据失败:', error)
  }
}

onMounted(() => {
  updateChart()
})
</script>
